<?php

namespace App\WebSocket;

use App\Utils\LogHelp;
use App\Utils\WebSocketMessage;
use EasySwoole\Socket\AbstractInterface\ParserInterface;
use EasySwoole\Socket\Bean\Caller;
use EasySwoole\Socket\Bean\Response;
use EasySwoole\Socket\Client\WebSocket as WebSocketClient;
use Google\Protobuf\Any;
use Jubo\JuLiao\IM\Wx\Proto\TransportMessage;

/**
 * 解析器
 * Class WebSocketParser
 * @package App\WebSocket
 */
class WebSocketParser implements ParserInterface
{
    /**
     * 解码上来的消息
     * @param string $raw 消息内容
     * @param WebSocketClient $client 当前的客户端
     * @return Caller|null
     */
    public function decode($raw, $client): ?Caller
    {
        if (empty($raw)) {
            return null;
        }
        try {
            $data = json_decode($raw, true);
        } catch (\Exception $e) {
            // 解码失败
            LogHelp::error("解码失败【原数据:{$raw}】", 'websocket');
            return null;
        }

        $msgType = $data['msgType'] ?? '';
        if (empty($msgType)) {
            return null;
        }
        $content = $data['content'] ?? '';

        $caller = new Caller;
        $caller->setControllerClass(\App\WebSocket\Controller\Index::class);
        $caller->setAction(lcfirst($msgType));
        $caller->setArgs([
            'data' => [
                'msgType' => $msgType,
                'content' => $content,
                'checkType' => intval($data['checkType'] ?? 0),
            ],
        ]);

        return $caller;
    }

    /**
     * 打包下发的消息
     * @param Response $response 控制器返回的响应
     * @param WebSocketClient $client 当前的客户端
     * @return string|null
     */
    public function encode(Response $response, $client): ?string
    {
        return $response->getMessage() ?: null;
    }
}
